﻿using Dapper;
using ERPEF.Model;
using ERPService;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using System.Data;

namespace S4Project.Controllers
{
    [Route("api/[controller]/[action]")]
    [ApiController]
    [Consumes("application/json")]
    //基本资料：库存预警
    public class InventoryAlertsController : ControllerBase
    {
        private readonly MyDbContext myDbContext;
        private readonly bs_inventory_alertsService bs_inventory_alerts;
        private readonly bs_WarehouseService bs_Warehouse;

        public InventoryAlertsController(MyDbContext myDb, bs_inventory_alertsService bs_inventory_alertsService, bs_WarehouseService bs_WarehouseService)
        {
            myDbContext = myDb;
            bs_inventory_alerts = bs_inventory_alertsService;
            bs_Warehouse = bs_WarehouseService;
        }

        //分页 
        [HttpGet]
        public ActionResult<FenYe<bs_Inventory_Alerts>> GetFenYe(int currentPage, int pageSize, string where)
        {
            using (var conn = myDbContext.Database.GetDbConnection())
            {
                conn.Open();
                var parameters = new DynamicParameters();
                parameters.Add("pageSize", dbType: DbType.Int32, direction: ParameterDirection.Input, value: pageSize);
                parameters.Add("keyName", dbType: DbType.String, direction: ParameterDirection.Input, value: "ia_id"); // 更改为正确的列名
                parameters.Add("tableName", dbType: DbType.String, direction: ParameterDirection.Input, value: "bs_Inventory_Alerts"); // 更改为正确的表名
                parameters.Add("currentPage", dbType: DbType.Int32, direction: ParameterDirection.Input, value: currentPage);
                parameters.Add("where", dbType: DbType.String, direction: ParameterDirection.Input, value: where); // 添加 where 参数
                parameters.Add("row", dbType: DbType.Int32, direction: ParameterDirection.Output); // 修改为和存储过程中一致的参数名
                string sql = "[dbo].[FenYe]";
                var result = conn.Query<bs_Inventory_Alerts>(sql, parameters, commandType: CommandType.StoredProcedure);
                int row = parameters.Get<int>("row");
                FenYe<bs_Inventory_Alerts> fenYe = new FenYe<bs_Inventory_Alerts>()
                {
                    customersData = result,
                    Rows = row,
                };

                if (fenYe.customersData.Any())
                {
                    return fenYe;
                }
                else
                {
                    return Content("没有查到数据");
                }
            }
        }


        [HttpGet]
        public async Task<IActionResult> InventoryQuery(string w_Name, string ia_goods_name)
        {
            var Inv = await myDbContext.inv_goods_inventory
                .Where(i => i.igi_warehouse == w_Name && i.igi_name == ia_goods_name)
                .Select(i => i.igi_quantity)
                .ToListAsync();

            return Ok(Inv);
        }
        //添加
        [HttpPost]
        public async Task<IActionResult> Add(bs_Inventory_Alerts inventory_Alerts)
        {
            //inventory_Alerts.ia_system_inventory = 1125;//默认系统库存
            if (ModelState.IsValid)
            {
                try
                {
                    // 检查最低库存和最高库存与系统库存的对比
                    int difference = inventory_Alerts.ia_system_inventory;
                    //系统库存大于最大，小于最小才会有超限数量
                    if (difference > inventory_Alerts.ia_max_inventory)
                    {
                        // 超过超限数量
                        inventory_Alerts.ia_go_beyond = difference - inventory_Alerts.ia_max_inventory;
                    }
                    else if (difference < inventory_Alerts.ia_min_inventory)
                    {
                        // 小于超限数量，使用 "-" 符号进行添加
                        inventory_Alerts.ia_go_beyond = difference - inventory_Alerts.ia_min_inventory;
                    }
                    else
                    {
                        // 不超过超限数量，不进行添加
                        inventory_Alerts.ia_go_beyond = 0;
                    }
                }
                catch (Exception ex)
                {
                    // 异常处理：返回服务器错误信息
                    return StatusCode(StatusCodes.Status500InternalServerError, "服务器错误：" + ex.Message);
                }

                int result = await bs_inventory_alerts.Add(inventory_Alerts);
                if (result > 0)
                {
                    return Ok("添加成功");
                }
                else
                {
                    return BadRequest("添加失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //修改
        [HttpPut]
        public async Task<IActionResult> Update(bs_Inventory_Alerts inventory_Alerts)
        {
            inventory_Alerts.ia_system_inventory = 1125;//默认系统库存
            if (ModelState.IsValid)
            {
                try
                {
                    //系统库存
                    int difference = inventory_Alerts.ia_system_inventory;
                    //系统库存大于最大，小于最小才会有超限数量
                    if (difference > inventory_Alerts.ia_max_inventory)
                    {
                        // 超过超限数量，进行添加
                        inventory_Alerts.ia_go_beyond = difference - inventory_Alerts.ia_max_inventory;
                    }
                    else if (difference < inventory_Alerts.ia_min_inventory)
                    {
                        // 小于超限数量，使用 "-" 符号进行添加
                        inventory_Alerts.ia_go_beyond = difference - inventory_Alerts.ia_min_inventory;
                    }
                    else
                    {
                        // 不超过超限数量，不进行添加
                        inventory_Alerts.ia_go_beyond = 0;
                    }

                }
                catch (Exception ex)
                {
                    // 异常处理：返回服务器错误信息
                    return StatusCode(StatusCodes.Status500InternalServerError, "服务器错误：" + ex.Message);
                }

                int result = await bs_inventory_alerts.Update(inventory_Alerts);
                if (result > 0)
                {
                    return Ok("修改成功");
                }
                else
                {
                    return BadRequest("修改失败");
                }
            }
            else
            {
                return BadRequest(ModelState);
            }
        }

        //删除
        [HttpDelete("{ia_id}")]
        public async Task<IActionResult> Delete(int ia_id)
        {
            int result = await bs_inventory_alerts.Delete(ia_id);
            if (result > 0)
            {
                return Ok("删除成功！");
            }
            else
            {
                return NotFound("未找到");
            }
        }


        //查询仓库状态值==1 “正常”
        [HttpGet]
        public async Task<IActionResult> IQuery()
        {
            var warehouse = await bs_Warehouse.Query();

            // 筛选出状态为1的数据
            var filteredWarehouse = warehouse.Where(w => w.W_status == '1').ToList();

            if (filteredWarehouse.Any())
            {
                return Ok(filteredWarehouse);
            }
            else
            {
                return NotFound("没有符合条件的仓库数据");
            }
        }
        //查询物品属性
        [HttpGet]
        public async Task<IActionResult> Query()
        {
            var del = await bs_inventory_alerts.Query();
            if (del != null)
            {
                return Ok(del);
            }
            else
            {
                return NotFound("404");
            }
        }
        //查询物品名称
        [HttpGet]
        public async Task<IActionResult> ResQuery(string where)
        {
            var del = await bs_inventory_alerts.Query();
            var data = del.Where(w => w.di_type == where).ToList();
            if (data != null)
            {
                return Ok(data);
            }
            else
            {
                return NotFound("404");
            }
        }

        //查询字典--单位
        [HttpGet]
        public async Task<IActionResult> DictQuery()
        {
            var dic = await bs_inventory_alerts.DictQuery();
            var dict = dic.Where(w => w.dd_type == "type_unit").ToList();
            if (dict.Any())
            {
                return Ok(dict);
            }
            else
            {
                return NotFound("404");
            }
        }

    }
}
